import { fabric } from 'fabric'
import { ref } from 'vue'

export function useDrawing(getCanvas) {
  const isDrawing = ref(false)
  const drawingMode = ref('pencil')
  const drawingColor = ref('#000000')
  const drawingWidth = ref(2)

  // 启用/禁用绘图模式
  const toggleDrawing = (enabled) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    isDrawing.value = enabled
    fabricCanvas.isDrawingMode = enabled

    if (enabled) {
      // 设置绘图模式
      switch (drawingMode.value) {
        case 'pencil':
          fabricCanvas.freeDrawingBrush = new fabric.PencilBrush(fabricCanvas)
          break
        case 'spray':
          fabricCanvas.freeDrawingBrush = new fabric.SprayBrush(fabricCanvas)
          break
        case 'circle':
          fabricCanvas.freeDrawingBrush = new fabric.CircleBrush(fabricCanvas)
          break
      }

      // 设置画笔属性
      fabricCanvas.freeDrawingBrush.color = drawingColor.value
      fabricCanvas.freeDrawingBrush.width = drawingWidth.value
    }
  }

  // 设置绘图模式
  const setDrawingMode = (mode) => {
    drawingMode.value = mode
    if (isDrawing.value) {
      toggleDrawing(true) // 重新应用新的绘图模式
    }
  }

  // 设置画笔颜色
  const setDrawingColor = (color) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    drawingColor.value = color
    if (fabricCanvas.freeDrawingBrush) {
      fabricCanvas.freeDrawingBrush.color = color
    }
  }

  // 设置画笔宽度
  const setDrawingWidth = (width) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    drawingWidth.value = width
    if (fabricCanvas.freeDrawingBrush) {
      fabricCanvas.freeDrawingBrush.width = width
    }
  }

  // 添加基本图形
  const addShape = (type) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    let shape
    switch (type) {
      case 'rect':
        shape = new fabric.Rect({
          left: 100,
          top: 100,
          width: 100,
          height: 100,
          fill: drawingColor.value
        })
        break
      case 'circle':
        shape = new fabric.Circle({
          left: 100,
          top: 100,
          radius: 50,
          fill: drawingColor.value
        })
        break
      case 'triangle':
        shape = new fabric.Triangle({
          left: 100,
          top: 100,
          width: 100,
          height: 100,
          fill: drawingColor.value
        })
        break
      case 'line':
        shape = new fabric.Line([50, 50, 150, 150], {
          stroke: drawingColor.value,
          strokeWidth: drawingWidth.value
        })
        break
    }

    if (shape) {
      fabricCanvas.add(shape)
      fabricCanvas.setActiveObject(shape)
      fabricCanvas.renderAll()
    }
  }

  return {
    isDrawing,
    drawingMode,
    drawingColor,
    drawingWidth,
    toggleDrawing,
    setDrawingMode,
    setDrawingColor,
    setDrawingWidth,
    addShape
  }
} 